﻿///***************************************************************
/// 시  스  템 : Updms.Car
/// 단위시스템 : CAR
/// 계      층 : Presentation Layer
/// 프로그램명 : Car2013r
/// 파  일  명 : Car2013r.aspx.cs
/// 설      명 : 월별차량비용내역 - 달력형태
///***************************************************************
/// 수정ID 일자       이름     내용
///---------------------------------------------------------------
/// CH001  2010-07-12 송시명   최초 작성
///***************************************************************
using System;
using System.Data;
using System.Collections;
using System.Web.UI;
using System.Web.UI.WebControls;

using SMFramework.Data;
using SMFramework.Utility;

using Base.AppFramework;
using Base.Dac;
using Updms.Car.Exe;


namespace Updms.Car
{
	public partial class Car2013r : Updms.Common.BaseClass.PageBase
	{
		#region 전역영역

		//프로그램상수
		public static readonly string PID = "Car2013r";
		public static readonly string gs_path_info = "/updms/Car/" + PID + ".aspx";

		Global global = new Global();
		CommCode.Etc etc = new CommCode.Etc(LANG_SET);

		//검색
		protected string kw1 = "";	//차량코드
		protected string kw2 = "";	//기준년월

		//메뉴 선택값
		protected string gs_sm = "";

		//합계
		decimal ld_m01 = 0;
		decimal ld_m02 = 0;
		decimal ld_m03 = 0;
		decimal ld_m04 = 0;
		decimal ld_m05 = 0;
		decimal ld_m06 = 0;
		decimal ld_m07 = 0;
		decimal ld_m08 = 0;
		decimal ld_m09 = 0;
		decimal ld_m10 = 0;
		decimal ld_m11 = 0;
		decimal ld_m12 = 0;
		decimal ld_total = 0;

		#endregion

		#region Page_Load, OnPageLoad

		protected void Page_Load(object sender, EventArgs e)
		{
			SetInit();
			if (!Page.IsPostBack)
			{
				// 최초 화면 로딩시 처리해야 할 부분
				OnPageLoad();
			}
		}

		// OnPageLoad
		private void OnPageLoad()
		{
			SetLiterals(global.GetLabelInfoByPgmId(PID, LANG_SET));
			SetLayout();
			SetCarInfo();
			SetBaseYear(ddl_search_car_id.SelectedValue);
			SetSearchParameter();
			SearchProcess();
		}

		#endregion

		#region InitializeComponent

		private void InitializeComponent()
		{
			this.Load += new System.EventHandler(this.Page_Load);
			this.PreRender += new System.EventHandler(this.Page_PreRender);
		}

		#endregion	

		#region SetInit, SetSearchParameter

		//초기값설정
		private void SetInit()
		{
			lbl_search_flag.Text = "INIT";

			gs_sm = (Request.QueryString["sm"] == null || Request.QueryString["sm"].Trim().Length != 7)
					? global.GetDirDepth(PID) : Request.QueryString["sm"].ToString();
		}

		//검색파라미터
		private void SetSearchParameter()
		{
			switch (lbl_search_flag.Text.Trim().ToUpper())
			{
				case "INIT":
					if (String.IsNullOrEmpty(Request.QueryString["kw1"]))	// url에 값이 없으면
					{
						kw1 = ddl_search_car_id.SelectedValue;
					}
					else
					{
						kw1 = Server.UrlDecode(Request.QueryString["kw1"]);
						ddl_search_car_id.SelectedValue = kw1;
					}

					if (String.IsNullOrEmpty(Request.QueryString["kw2"]))	// url에 값이 없으면
					{
						kw2 = ddl_search_base_year.SelectedValue + "-" + ddl_search_base_month.SelectedValue;
					}
					else
					{
						kw2 = Server.UrlDecode(Request.QueryString["kw2"]);
						ddl_search_base_year.SelectedValue = kw2.Substring(0, 4).ToString();
						ddl_search_base_month.SelectedValue = kw2.Substring(5, 2).ToString();
					}
					
					break;
				case "SEARCH":
					kw1 = ddl_search_car_id.SelectedValue;
					kw2 = ddl_search_base_year.SelectedValue + "-" + ddl_search_base_month.SelectedValue;
					break;
			}
		}


		#endregion

		#region 마스터 Method (SetLayout, SetCarInfo, SetBaseYear)

		//레이아웃
		private void SetLayout()
		{
			etc.SetLayout(rbl_layout);
		}

		//차량ID
		private void SetCarInfo()
		{
			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();
			Car1010m_NT _Car1010m_NT = new Car1010m_NT();

			lo_dp.AddProperty("ls_use_yn", typeof(string), "Y");	//사용여부가 Y인것만

			lo_ds.Merge(_Car1010m_NT.GetCarInfoList(lo_dp));

			ddl_search_car_id.Items.Clear();
			ddl_search_car_id.DataSource = lo_ds;
			ddl_search_car_id.DataMember = "UPDMS_CAR_INFO";
			ddl_search_car_id.DataTextField = "Text";
			ddl_search_car_id.DataValueField = "Value";
			ddl_search_car_id.DataBind();
		}


		//기준년도 설정
		private void SetBaseYear(string ls_car_id)
		{
			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();
			ddl_search_base_year.Items.Clear();

			lo_dp.AddProperty("ls_car_id", typeof(string), ls_car_id);

			using (Car1010m_NT _Car1010m_NT = new Car1010m_NT())
			{
				lo_ds.Merge(_Car1010m_NT.GetMinNMaxExpenseDt(lo_dp));
			}

			if (DataSetUtil.GetFldInt(lo_ds, "UPDMS_CAR_INFO", "Min_Dt_Y") > 0)
			{
				int li_min_dt_y = DataSetUtil.GetFldInt(lo_ds, "UPDMS_CAR_INFO", "Min_Dt_Y");
				int li_max_dt_y = Convert.ToInt32(DateUtil.GetYearEx(0, "yyyy"));

				for (int i = li_min_dt_y; i <= li_max_dt_y; i++)
				{
					string ls_year = i.ToString();
					ddl_search_base_year.Items.Add(new ListItem(ls_year, ls_year));
				}

				ddl_search_base_year.SelectedValue = DateUtil.GetYearEx(0, "yyyy"); //현재년도
				ddl_search_base_month.SelectedValue = DateUtil.GetMonthEx(0, "MM"); //현재월
			}
			else
			{
				ddl_search_base_year.Items.Add(new ListItem(DateUtil.GetYearEx(0, "yyyy"), DateUtil.GetYearEx(0, "yyyy")));
			}
		}


		#endregion

		#region 디테일 Method (SetPrevNextMonth, SetEnabledMonthBtn, SetThisMonth, SetThisYear, SetChartByDiv)

		//이전달, 다음달버튼 누르면
		private void SetPrevNextMonth(int pi_month_cnt)
		{
			string ls_ym = ddl_search_base_year.SelectedValue + "-" + ddl_search_base_month.SelectedValue;
			string ls_calc_ym = DateUtil.GetCalcMonth(ls_ym, pi_month_cnt, "yyyy-MM");

            if (WebControlUtil.CheckDdlValue(ddl_search_base_year, ls_calc_ym.Substring(0, 4).ToString()))
			{
				ddl_search_base_year.SelectedValue = ls_calc_ym.Substring(0, 4).ToString();
				ddl_search_base_month.SelectedValue = ls_calc_ym.Substring(5, 2).ToString();
			}
			
			//버튼처리
			SetEnabledMonthBtn();
		}

		//이전년, 다음년버튼 누르면
		private void SetPrevNextYear(int pi_year_cnt)
		{
			int li_calc_year = Convert.ToInt32(ddl_search_base_year.SelectedValue) + pi_year_cnt;	//2008 + (-1)

			if (WebControlUtil.CheckDdlValue(ddl_search_base_year, li_calc_year.ToString()))
			{
				ddl_search_base_year.SelectedValue = li_calc_year.ToString();
			}

			//버튼처리
			SetEnabledYearBtn();
		}
		
		//이전달, 다음달버튼 처리
		private void SetEnabledMonthBtn()
		{
			ibtn_prev_month.Enabled 
				= (ddl_search_base_year.SelectedIndex == 0 && ddl_search_base_month.SelectedIndex == 0) ? false : true;
			
			ibtn_next_month.Enabled 
				= (ddl_search_base_year.SelectedIndex == ddl_search_base_year.Items.Count - 1 && ddl_search_base_month.SelectedIndex == 11) ? false : true;
		}

		//이전년, 다음년버튼 처리
		private void SetEnabledYearBtn()
		{
			ibtn_prev_year.Enabled
				= (ddl_search_base_year.SelectedIndex == 0) ? false : true;

			ibtn_next_year.Enabled
				= (ddl_search_base_year.SelectedIndex == ddl_search_base_year.Items.Count - 1) ? false : true;
		}
		
		//당월설정
		private void SetThisMonth()
		{
			string ls_this_ym = DateUtil.GetNow("yyyy-MM");
			ddl_search_base_year.SelectedValue = ls_this_ym.Substring(0, 4).ToString();
			ddl_search_base_month.SelectedValue = ls_this_ym.Substring(5, 2).ToString();
			SetEnabledMonthBtn();
		}

		//당년설정
		private void SetThisYear()
		{
			string ls_this_year = DateUtil.GetNow("yyyy");
			ddl_search_base_year.SelectedValue = ls_this_year;
			SetEnabledYearBtn();
		}

		//구분별 라인챠트
		private void SetChartByDiv(GridView gv, int first_month_idx, int row_idx)
		{
			//시리즈
			chart_line.Data.Series = 1;
			string series = String.Empty;

			series = (row_idx < 0)
						? "Total"
						: ConversionUtil.ExtractStrBtwnChar(gv.Rows[row_idx].Cells[0].Text, ";\">", "</a>");

			chart_line.Series[0].Text = series;

			//초기화
			chart_line.Data.Clear();

			for (int i = 0; i < 12; i++)
			{
				//수동으로 데이터 바인딩
				int data = 0;
				data = (row_idx < 0)
						? Convert.ToInt32(ConversionUtil.RemoveComma(gv.FooterRow.Cells[i + first_month_idx].Text)) //총계
						: Convert.ToInt32(ConversionUtil.RemoveComma(gv.Rows[row_idx].Cells[i + first_month_idx].Text));
				
				chart_line.Data[0, i] = data;

				//X축 라벨링
				string ls_base_dt = "'" + ddl_search_base_year.SelectedValue.Substring(2, 2) + "." + DateUtil.ConvertMonthFormat((i + 1).ToString());
				chart_line.AxisX.Labels[i] = ls_base_dt;

				//0은 안보여준다
				chart_line.Points[0, i].PointLabels.Visible = (chart_line.Data[0, i] > 0);
			}

			mpe_chart_line.Show();
		}

		#endregion

		#region 리스트 (SelectMonthly, SelectYearly, SearchProcess)

		//월별
		private void SelectMonthly()
		{
			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();

			lo_dp.AddProperty("ls_car_id", typeof(string), kw1);
			lo_dp.AddProperty("ls_base_ym", typeof(string), kw2);
			lo_dp.AddProperty("ls_lang_set", typeof(string), LANG_SET);

			using (Car2013r_NT _Car2013r_NT = new Car2013r_NT())
			{
				try
				{
					lo_ds.Merge(_Car2013r_NT.GetMonthlyUsingList(lo_dp));

					GridView1.DataSource = lo_ds.Tables["MONTHLY_USING_LIST"];
					GridView1.DataBind();

					//Base.AppFramework.SMEventLog.WriteDataLog("", lo_ds, "MONTHLY_COST_SUMMARY");

					int li_refuelling = DataSetUtil.GetFldInt(lo_ds, "MONTHLY_COST_SUMMARY", 0, "Amount");	//주유
					int li_service = DataSetUtil.GetFldInt(lo_ds, "MONTHLY_COST_SUMMARY", 1, "Amount");	//정비
					int li_traffic = DataSetUtil.GetFldInt(lo_ds, "MONTHLY_COST_SUMMARY", 2, "Amount");	//주차,통행료
					int li_washing = DataSetUtil.GetFldInt(lo_ds, "MONTHLY_COST_SUMMARY", 3, "Amount");	//세차
					int li_total = li_refuelling + li_service + li_traffic + li_washing;

					ltr_refuelling_m.Text = ConversionUtil.AddComma(li_refuelling.ToString());
					ltr_service_m.Text = ConversionUtil.AddComma(li_service.ToString());
					ltr_traffic_m.Text = ConversionUtil.AddComma(li_traffic.ToString());
					ltr_washing.Text = ConversionUtil.AddComma(li_washing.ToString());
					ltr_total_m.Text = ConversionUtil.AddComma(li_total.ToString());
					
				}catch (Exception ex)
				{
					SMEventLog.WriteExceptionLog(ex);
				}
			}
			lbl_this_month.Text = DateUtil.ConvertDateMask(kw2, "yyyy-MM", LANG_SET);
		}

		//연간
		private void SelectYearly()
		{
			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();

			//검색
			lo_dp.AddProperty("ls_car_id", typeof(string), kw1);
			lo_dp.AddProperty("ls_base_ym", typeof(string), kw2);
			lo_dp.AddProperty("ls_lang_set", typeof(string), LANG_SET);

			using (Car2013r_NT _Car2013r_NT = new Car2013r_NT())
			{
				try
				{
					lo_ds.Merge(_Car2013r_NT.GetYearlyUsingList(lo_dp));

					GridView2.DataSource = lo_ds.Tables["YEARLY_USING_LIST"];
					GridView2.DataBind();

					int li_refuelling = DataSetUtil.GetFldInt(lo_ds, "YEARLY_COST_SUMMARY", 0, "Amount");	//주유
					int li_service = DataSetUtil.GetFldInt(lo_ds, "YEARLY_COST_SUMMARY", 1, "Amount");	//정비
					int li_traffic = DataSetUtil.GetFldInt(lo_ds, "YEARLY_COST_SUMMARY", 2, "Amount");	//주차,통행료	
					int li_washing = DataSetUtil.GetFldInt(lo_ds, "YEARLY_COST_SUMMARY", 3, "Amount");	//세차
					int li_total = li_refuelling + li_service + li_traffic + li_washing;

					ltr_refuelling_y.Text = ConversionUtil.AddComma(li_refuelling.ToString());
					ltr_service_y.Text = ConversionUtil.AddComma(li_service.ToString());
					ltr_traffic_y.Text = ConversionUtil.AddComma(li_traffic.ToString());
					ltr_washing_y.Text = ConversionUtil.AddComma(li_washing.ToString());
					ltr_total_y.Text = ConversionUtil.AddComma(li_total.ToString());

					GridView3.DataSource = lo_ds.Tables["YEARLY_COST_LIST"];
					GridView3.DataBind();
				}
				catch (Exception ex)
				{
					SMEventLog.WriteExceptionLog(ex);
				}
			}

			lbl_this_year.Text = DateUtil.GetCalcMonth(kw2, 0, "yyyy");
		}

		//검색
		private void SearchProcess()
		{
			lbl_search_flag.Text = "SEARCH";
			SetSearchParameter();

			switch (rbl_layout.SelectedValue)
			{
				case "AH001":	//월별
					table_monthly.Visible = true;
					table_yearly.Visible = false;
					SetEnabledMonthBtn();
					SelectMonthly();
					break;
				case "AH002":	//년도별
					table_monthly.Visible = false;
					table_yearly.Visible = true;
					SetEnabledYearBtn();
					SelectYearly();
					break;
				default:
					table_monthly.Visible = true;
					table_yearly.Visible = false;
					SetEnabledYearBtn();
					SelectMonthly();
					break;
			}
		}

		#endregion

		#region Page_PreRender, ChangePageMode

		// Page_PreRender
		private void Page_PreRender(object sender, System.EventArgs e)
		{
			if (!Page.IsPostBack)
			{
				using (AccessCheck access = new AccessCheck())
				{
					//접근권한 체크
					if (!access.CheckPgmAccessGrant(PID, USER_ID, ACCESS_LOG_INFO))
					{
						Response.Redirect(URL_NO_AUTHORITY_REDIRECT_BASE);	//사용자의 권한은 요청하신 페이지를 볼 수 없습니다
					}
				}
			}
			ChangePageMode();
		}

		//ChangePageMode
		private void ChangePageMode()
		{
			SetGridViewHeader(global.GetColumnListByPgmId(PID, LANG_SET));
		}

		#endregion

		#region GridView이벤트

		//RowDataBound
		protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
		{
			if (e.Row.RowType == DataControlRowType.DataRow)
			{
				for (int i = 0; i < e.Row.Cells.Count; i++)
				{
					e.Row.Cells[i].Attributes.Add("onMouseOver", GRID_ONMOUSEOVER_COLOR);
					e.Row.Cells[i].Attributes.Add("onMouseOut", GRID_ONMOUSEOUT_COLOR);
				}
			}
		}

		//RowDataBound
		protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
		{
			if (e.Row.RowType == DataControlRowType.DataRow)
			{
				for (int i = 0; i < e.Row.Cells.Count; i++)
				{
					e.Row.Cells[i].Attributes.Add("onMouseOver", GRID_ONMOUSEOVER_COLOR);
					e.Row.Cells[i].Attributes.Add("onMouseOut", GRID_ONMOUSEOUT_COLOR);
				}

				//일자
				e.Row.Cells[0].Text = (e.Row.RowIndex + 1).ToString();
			}
		}

		//RowDataBound
		protected void GridView3_RowDataBound(object sender, GridViewRowEventArgs e)
		{
			if (e.Row.RowType == DataControlRowType.DataRow)
			{
				e.Row.Attributes.Add("onMouseOver", GRID_ONMOUSEOVER_COLOR);
				e.Row.Attributes.Add("onMouseOut", GRID_ONMOUSEOUT_COLOR);

				e.Row.Cells[0].Text = "<a href=\"#\" onclick=\"viewChartByDiv('" + e.Row.RowIndex.ToString() + "');\">" + e.Row.Cells[0].Text + "</a>";

				//합계
				ld_m01 += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "M01"));
				ld_m02 += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "M02"));
				ld_m03 += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "M03"));
				ld_m04 += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "M04"));
				ld_m05 += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "M05"));
				ld_m06 += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "M06"));
				ld_m07 += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "M07"));
				ld_m08 += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "M08"));
				ld_m09 += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "M09"));
				ld_m10 += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "M10"));
				ld_m11 += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "M11"));
				ld_m12 += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "M12"));
				ld_total += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "Total_Amt"));
			}

			//Footer에 합계 바인딩
			if (e.Row.RowType == DataControlRowType.Footer)
			{
				e.Row.Cells[0].Text = "<a href=\"#\" onclick=\"viewChartByDiv('-1');\">Total</a>";
				e.Row.Cells[0].Attributes.Add("class", "total");
				e.Row.Cells[1].Text = ld_m01.ToString("#,###,##0");
				e.Row.Cells[1].Attributes.Add("class", "money");
				e.Row.Cells[2].Text = ld_m02.ToString("#,###,##0");
				e.Row.Cells[2].Attributes.Add("class", "money");
				e.Row.Cells[3].Text = ld_m03.ToString("#,###,##0");
				e.Row.Cells[3].Attributes.Add("class", "money");
				e.Row.Cells[4].Text = ld_m04.ToString("#,###,##0");
				e.Row.Cells[4].Attributes.Add("class", "money");
				e.Row.Cells[5].Text = ld_m05.ToString("#,###,##0");
				e.Row.Cells[5].Attributes.Add("class", "money");
				e.Row.Cells[6].Text = ld_m06.ToString("#,###,##0");
				e.Row.Cells[6].Attributes.Add("class", "money");
				e.Row.Cells[7].Text = ld_m07.ToString("#,###,##0");
				e.Row.Cells[7].Attributes.Add("class", "money");
				e.Row.Cells[8].Text = ld_m08.ToString("#,###,##0");
				e.Row.Cells[8].Attributes.Add("class", "money");
				e.Row.Cells[9].Text = ld_m09.ToString("#,###,##0");
				e.Row.Cells[9].Attributes.Add("class", "money");
				e.Row.Cells[10].Text = ld_m10.ToString("#,###,##0");
				e.Row.Cells[10].Attributes.Add("class", "money");
				e.Row.Cells[11].Text = ld_m11.ToString("#,###,##0");
				e.Row.Cells[11].Attributes.Add("class", "money");
				e.Row.Cells[12].Text = ld_m12.ToString("#,###,##0");
				e.Row.Cells[12].Attributes.Add("class", "money");
				e.Row.Cells[13].Text = ld_total.ToString("#,###,##0");
				e.Row.Cells[13].Attributes.Add("class", "money");
			}
		}

		#endregion

		#region 버튼이벤트

		//검색
		protected void ibtn_search_Click(object sender, EventArgs e)
		{
			SearchProcess();
		}

		//엑셀
		protected void ibtn_excel_Click(object sender, EventArgs e)
		{
			SetSearchParameter();

			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();

			lo_dp.AddProperty("ls_car_id", typeof(string), kw1);
			lo_dp.AddProperty("ls_base_ym", typeof(string), kw2);
			lo_dp.AddProperty("ls_lang_set", typeof(string), LANG_SET);

			using (Car2013r_NT _Car2013r_NT = new Car2013r_NT())
			{
				lo_ds.Merge(_Car2013r_NT.GetMonthlyUsingList(lo_dp));
			}
			string fileName = PID + "(" + global.GetMenuTitle(PID, LANG_SET) + ")";
			ExcelUtil.CreateExcelFileX(this.Page, fileName, lo_ds, SetExcelHeaderX(global.GetColumnListByPgmId(PID, LANG_SET)));
		}
		
		//이전달
		protected void ibtn_prev_month_Click(object sender, EventArgs e)
		{
			SetPrevNextMonth(-1);
			SearchProcess();
		}
		
		//다음달
		protected void ibtn_next_month_Click(object sender, EventArgs e)
		{
			SetPrevNextMonth(1);
			SearchProcess();
		}

		//당월
		protected void ibtn_this_month_Click(object sender, EventArgs e)
		{
			SetThisMonth();
			SearchProcess();
		}

		//이전년
		protected void ibtn_prev_year_Click(object sender, EventArgs e)
		{
			SetPrevNextYear(-1);
			SearchProcess();
		}

		//다음년
		protected void ibtn_next_year_Click(object sender, EventArgs e)
		{
			SetPrevNextYear(1);
			SearchProcess();
		}

		//당년
		protected void ibtn_this_year_Click(object sender, EventArgs e)
		{
			SetThisYear();
			SearchProcess();
		}

		//구분별챠트 생성
		protected void lbtn_set_chart_Click(object sender, EventArgs e)
		{
			int li_first_month_idx = 1;	//1월의 index값
			SetChartByDiv(GridView3, li_first_month_idx, Convert.ToInt32(h_row_idx.Value));
		}

		#endregion

	}
}
